#include "patheditview.h"
#include "ui_patheditview.h"
#include "onemap.h"
#include <QMessageBox>
extern double g_mapRatio;

PathEditView::PathEditView(OneMap *oneMapIn, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PathEditView)
{
    ui->setupUi(this);
    oneMap=oneMapIn;

    model_stationInfo = new QStandardItemModel();

    connect(ui->tableView_stationInfo,SIGNAL(clicked(QModelIndex)),this,SLOT( showChooseStation_slot() ));
}

PathEditView::~PathEditView()
{
    delete ui;
}

void PathEditView::showView_slot()
{
    showStationInfo();
    show();
}

void PathEditView::showChooseStation_slot()
{
    int row= ui->tableView_stationInfo->currentIndex().row();
    QAbstractItemModel *model = ui->tableView_stationInfo->model ();
    QModelIndex index = model->index(row,6);//选中行第一列的内容
    QVariant data = model->data(index);
    ui->lineEdit_originStartAngle->setText(data.toString());
    ui->lineEdit_newStartAngle->setText(data.toString());


    index = model->index(row,7);//选中行第一列的内容
    data = model->data(index);
    ui->lineEdit_originEndAngle->setText(data.toString());
    ui->lineEdit_newEndAngle->setText(data.toString());

    index = model->index(row,2);
    data = model->data(index);
    ui->lineEdit_p1x->setText(data.toString());

    index = model->index(row,3);
    data = model->data(index);
    ui->lineEdit_p1y->setText(data.toString());

    index = model->index(row,4);
    data = model->data(index);
    ui->lineEdit_p2x->setText(data.toString());

    index = model->index(row,5);
    data = model->data(index);
    ui->lineEdit_p2y->setText(data.toString());

    index = model->index(row,0);
    data = model->data(index);
    ui->lineEdit_pathId->setText(data.toString());




}

void PathEditView::showStationInfo()
{
    std::list<MapPath *> tmpList=oneMap->getPaths_sort();

    model_stationInfo->clear();
    QStringList labels6 = QObject::trUtf8("id,名称,物理p1x,物理p1y,物理p2x,物理p2y,开始角度,结束角度,速度,避障").simplified().split(",");
    model_stationInfo->setHorizontalHeaderLabels(labels6);
    ui->tableView_stationInfo->setColumnWidth(1,120);
    //定义item
    QStandardItem* item = 0;

    int i=0;
    for (auto p : tmpList)
    {
//        if(MapPath::Map_Path_Type_Cubic_Bezier==p->getPathType())
//        {
            item = new QStandardItem(QString::number(p->getId()));
            model_stationInfo->setItem(i,0,item);
            item = new QStandardItem(QString::fromStdString(p->getName()));
            model_stationInfo->setItem(i,1,item);
            item = new QStandardItem(QString::number(p->getP1x_real(),'f',3));
            model_stationInfo->setItem(i,2,item);
            item = new QStandardItem(QString::number(p->getP1y_real(),'f',3));
            model_stationInfo->setItem(i,3,item);
            item = new QStandardItem(QString::number(p->getP2x_real(),'f',3));
            model_stationInfo->setItem(i,4,item);
            item = new QStandardItem(QString::number(p->getP2y_real(),'f',3));
            model_stationInfo->setItem(i,5,item);
            double tmpAngle1,tmpAngle2;
            MapPoint *tmpStartPoint=oneMap->getPointById(p->getStart());
            MapPoint *tmpEndPoint=oneMap->getPointById(p->getEnd());
            if(nullptr!=tmpStartPoint && nullptr!=tmpEndPoint)
            {
                tmpAngle1=atan2(p->getP1y_real()-tmpStartPoint->getRealY(),p->getP1x_real()-tmpStartPoint->getRealX());
                tmpAngle2=atan2(tmpEndPoint->getRealY()-p->getP2y_real(),tmpEndPoint->getRealX()-p->getP2x_real());
            }


            item = new QStandardItem(QString::number(tmpAngle1*180.0/M_PI,'f',3));
            model_stationInfo->setItem(i,6,item);

            item = new QStandardItem(QString::number(tmpAngle2*180.0/M_PI,'f',3));
            model_stationInfo->setItem(i,7,item);


            item = new QStandardItem(QString::number(p->getSpeed(),'f',3));
            model_stationInfo->setItem(i,8,item);

            QString tmpBarrier;
            switch(p->getBarrierType())
            {
            case E_PATH_BARRIER_TYPE_NODETECT:
                tmpBarrier="不避障";
                break;
            case E_PATH_BARRIER_TYPE_COMMON:
                tmpBarrier="普通避障";
                break;
            case E_PATH_BARRIER_TYPE_NARROW:
                tmpBarrier="窄通道";
                break;
            case E_PATH_BARRIER_TYPE_DONOTHING:
                tmpBarrier="不修改";
                break;

            }
            item = new QStandardItem(tmpBarrier);
            model_stationInfo->setItem(i,9,item);

            i++;
//        }


    }

    ui->tableView_stationInfo->setModel(model_stationInfo);
    ui->tableView_stationInfo->resizeColumnToContents(0);
    ui->tableView_stationInfo->resizeColumnToContents(1);
    ui->tableView_stationInfo->resizeColumnToContents(2);
    ui->tableView_stationInfo->show();
}

void PathEditView::on_pushButton_setStartAngle_clicked()
{
    int pathId=ui->lineEdit_pathId->text().toInt();
    double newAngle=ui->lineEdit_newStartAngle->text().toDouble()*M_PI/180.0;
    double ratio=ui->lineEdit_newTransitionRatioStart->text().toDouble();
    setPathStartAngle(pathId,newAngle,ratio);


//    int tmpKey=oneMap->modifyPointId(oldstationId, newId,newName.toStdString());
//    if(1==tmpKey)
//    {
//        QMessageBox::information(this,QStringLiteral("提示"),"失败：新id号已经被站点使用！");
//        return ;
//    }
    emit updateMapShow_signal();
    showStationInfo();
    QMessageBox::information(this,QStringLiteral("提示"),"修改开始角度成功！");
}

void PathEditView::on_pushButton_setEndAngle_clicked()
{
    int pathId=ui->lineEdit_pathId->text().toInt();
    double newAngle=ui->lineEdit_newEndAngle->text().toDouble()*M_PI/180.0;
    double ratio=ui->lineEdit_newTransitionRatioEnd->text().toDouble();
    setPathEndAngle(pathId,newAngle,ratio);

//    int tmpKey=oneMap->modifyPointId(oldstationId, newId,newName.toStdString());
//    if(1==tmpKey)
//    {
//        QMessageBox::information(this,QStringLiteral("提示"),"失败：新id号已经被站点使用！");
//        return ;
//    }
    emit updateMapShow_signal();
    showStationInfo();
    QMessageBox::information(this,QStringLiteral("提示"),"修改终止角度成功！");
}

void PathEditView::on_pushButton_setAllSplineTransitionAngleSmooth_clicked()
{
    std::list<MapPath *> tmpList=oneMap->getPaths();
    double ratio=ui->lineEdit_newTransitionRatioStart->text().toDouble();

    int i=0;
    for (auto tmpPath1 : tmpList)
    {
        if(MapPath::Map_Path_Type_Cubic_Bezier==tmpPath1->getPathType())
        {
            double tmpEndAngle;
            MapPoint *tmpStartPoint=oneMap->getPointById(tmpPath1->getStart());
            MapPoint *tmpEndPoint=oneMap->getPointById(tmpPath1->getEnd());
            if(nullptr!=tmpStartPoint && nullptr!=tmpEndPoint)
            {
                tmpEndAngle=atan2(tmpEndPoint->getRealY()-tmpPath1->getP2y_real(),tmpEndPoint->getRealX()-tmpPath1->getP2x_real());
                for (auto tmpPath2 : tmpList)
                {
                    if(MapPath::Map_Path_Type_Cubic_Bezier==tmpPath2->getPathType())
                    {
                        if(tmpPath1->getEnd()==tmpPath2->getStart()
                                && tmpPath1->getIsBackMove()==tmpPath2->getIsBackMove()
                                && tmpPath1->getStart()!=tmpPath2->getEnd())
                        {
                            //设置path2 start angle= path1 end angle
                            setPathStartAngle(tmpPath2->getId(),tmpEndAngle,ratio);

                            i++;
                        }

                    }
                }

            }



        }


    }

    emit updateMapShow_signal();
    showStationInfo();
    QString tmpNote="修改连续样条曲线衔接角度成功，共修改次数:";
    tmpNote+=QString::number(i);
    QMessageBox::information(this,QStringLiteral("提示"),tmpNote);
}

int PathEditView::setPathStartAngle(int pathId,double newAngle,double controlRatio)
{
    qDebug()<<"setPathStartAngle pathId"<<pathId<<"newAngle"<<newAngle<<"controlRatio"<<controlRatio;

    MapPath *tmpPath=oneMap->getPathById(pathId);
    MapPoint *tmpStartPoint=oneMap->getPointById(tmpPath->getStart());
    MapPoint *tmpEndPoint=oneMap->getPointById(tmpPath->getEnd());

    double p1x,p1y,p2x,p2y;
    p1x=tmpStartPoint->getRealX();
    p1y=tmpStartPoint->getRealY();
    p2x=tmpEndPoint->getRealX();
    p2y=tmpEndPoint->getRealY();


    double totalLength=sqrt((p1x-p2x)*(p1x-p2x)+(p1y-p2y)*(p1y-p2y));
    double plength=controlRatio*totalLength;

    double newp1x=p1x+plength*cos(newAngle);
    double newp1y=p1y+plength*sin(newAngle);


    tmpPath->setP1x(newp1x/g_mapRatio);
    tmpPath->setP1y(newp1y/g_mapRatio);
    tmpPath->setP1x_real(newp1x);
    tmpPath->setP1y_real(newp1y);
    return 1;
}

int PathEditView::setPathEndAngle(int pathId, double newAngle, double controlRatio)
{
    qDebug()<<"setPathEndAngle pathId"<<pathId<<"newAngle"<<newAngle<<"controlRatio"<<controlRatio;
    MapPath *tmpPath=oneMap->getPathById(pathId);
    MapPoint *tmpStartPoint=oneMap->getPointById(tmpPath->getStart());
    MapPoint *tmpEndPoint=oneMap->getPointById(tmpPath->getEnd());

    double p1x,p1y,p2x,p2y;
    p1x=tmpStartPoint->getRealX();
    p1y=tmpStartPoint->getRealY();
    p2x=tmpEndPoint->getRealX();
    p2y=tmpEndPoint->getRealY();

    double totalLength=sqrt((p1x-p2x)*(p1x-p2x)+(p1y-p2y)*(p1y-p2y));
    double plength=controlRatio*totalLength;

    double newp1x=p2x+plength*cos(newAngle+M_PI);
    double newp1y=p2y+plength*sin(newAngle+M_PI);


    tmpPath->setP2x(newp1x/g_mapRatio);
    tmpPath->setP2y(newp1y/g_mapRatio);
    tmpPath->setP2x_real(newp1x);
    tmpPath->setP2y_real(newp1y);
    return 1;
}

void PathEditView::on_pushButton_setNewPathId_clicked()
{

    int oldstationId=ui->lineEdit_pathId->text().toInt();
    int newId=ui->lineEdit_newId->text().toInt();

    int tmpKey=oneMap->modifyPathId(oldstationId, newId);
    switch(tmpKey)
    {
    case 1:

        break;
    case 0:
        QMessageBox::information(this,QStringLiteral("提示"),"失败：id号不存在！");
        return ;
        break;
    case -1:
        QMessageBox::information(this,QStringLiteral("提示"),"失败：新id号已经被使用,请先修改新id！");
        return ;
        break;

    default:
        QMessageBox::information(this,QStringLiteral("提示"),"失败！");
        return;
    }

//    emit sig_propertyChanged(tmpPoint);
    emit updateMapShow_signal();//会导致其它元素ｉｄ也变了，所以要全部更新．
    showStationInfo();
    QMessageBox::information(this,QStringLiteral("提示"),"修改路径id成功！");
}

void PathEditView::on_pushButton_setAllPathVelocity_clicked()
{
    QMessageBox message(QMessageBox::Question, "提示", "是否修改全部路径速度?"
                        , QMessageBox::Yes|QMessageBox::No , NULL);
    if(message.exec() == QMessageBox::No)
    {
        return;
    }
    std::list<MapPath *> paths=oneMap->getPaths();
    double tmpSpeed=ui->lineEdit_allPathVelocity->text().toDouble();
    for(auto s:paths)
    {
        s->setSpeed(tmpSpeed);
    }
    emit updateMapShow_signal();//会导致其它元素ｉｄ也变了，所以要全部更新．
    showStationInfo();
    QMessageBox::information(this,QStringLiteral("提示"),"修改全部路径速度成功！");
}

void PathEditView::on_pushButton_setAllBarrierMode_clicked()
{
    QMessageBox message(QMessageBox::Question, "提示", "是否修改全部路径避障碍策略?"
                        , QMessageBox::Yes|QMessageBox::No , NULL);
    if(message.exec() == QMessageBox::No)
    {
        return;
    }
    std::list<MapPath *> paths=oneMap->getPaths();
    E_PATH_BARRIER_TYPE tmpBarrier=(E_PATH_BARRIER_TYPE)ui->comboBox_allPathBarrierMode->currentIndex();
    for(auto s:paths)
    {
        s->setBarrierType(tmpBarrier);
    }
    emit updateMapShow_signal();//会导致其它元素ｉｄ也变了，所以要全部更新．
    showStationInfo();
    QMessageBox::information(this,QStringLiteral("提示"),"修改全部路径避障碍策略成功！");
}
